import pandas as pd
from pyecharts.charts import Line, Bar, Pie, Radar, WordCloud, Page
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from time import sleep

# 设置全局主题
theme_config = ThemeType.CHALK
v_title = '可视化大屏展示'
# 表格和标题的颜色
table_color = ""
if theme_config == ThemeType.DARK:
    table_color = '#333333'
elif theme_config == ThemeType.CHALK:
    table_color = '#293441'
elif theme_config == ThemeType.PURPLE_PASSION:
    table_color = '#5B5C6E'
elif theme_config == ThemeType.ROMANTIC:
    table_color = '#F0E8CD'
elif theme_config == ThemeType.ESSOS:
    table_color = '#FDFCF5'
else:
    table_color = ''


# 饼状图
def get_pie():
    data = pd.read_excel('./xlsx_data/list_type.xlsx')
    data = data.head(10)
    data = data[['类型', '类型数量']].values.tolist()
    pie = Pie(init_opts=opts.InitOpts(width="1400px", height="720px", theme=ThemeType.CHALK))
    pie.add(series_name='类型数量', data_pair=data)
    pie.set_global_opts(
        title_opts=opts.TitleOpts(title="哔哩哔哩热门视频各类型信息"),
        legend_opts=opts.LegendOpts(
            pos_left="left",
            pos_top="middle",
            orient="vertial"
        )
    )
    pie.render('./templates/pie.html')


def get_pie2(num):
    df = pd.read_csv('./xlsx_data/ALLbilibili.csv')
    df = df.sort_values('播放量', ascending=False).reset_index()
    df = df[['UP主', '播放量', '弹幕', '点赞', '投币', '收藏', '转发']]
    data = df[['UP主', '播放量']].values.tolist()

    num_index = 15  # 分隔数量
    start = num * num_index
    end = num * num_index + num_index
    data_list = data[start:end]

    pie = Pie(init_opts=opts.InitOpts(width="1400px", height="720px", theme=ThemeType.CHALK))
    pie.add(series_name='播放量', data_pair=data_list)
    pie.set_global_opts(
        title_opts=opts.TitleOpts(title="哔哩哔哩热门视频播放量信息"),
        legend_opts=opts.LegendOpts(
            pos_left="left",
            pos_top="middle",
            orient="vertial"
        )
    )
    pie.render('./templates/pie2.html')
    return pie


# 折线图
def get_line():
    df = pd.read_excel("flask_test/xlsx_data/bilibili.xlsx")
    df2 = df[['点赞', '投币']].sort_values('点赞').reset_index()
    # 准备数据
    x_data = df2['点赞']
    y_data = df2['投币']

    # 生成折线图
    line = Line(init_opts=opts.InitOpts(width="1400px", height="720px", theme=ThemeType.CHALK))
    # 插入x轴和y轴
    line.add_xaxis(x_data)
    line.add_yaxis(
        series_name='投币',
        y_axis=y_data)

    # 设置全局配置项
    line.set_global_opts(
        xaxis_opts=opts.AxisOpts(name='点赞', type_='category'))
    line.set_global_opts(
        title_opts=opts.TitleOpts(title='投币与点赞对比'),
        yaxis_opts=opts.AxisOpts(name='投币', type_='value'))
    # 设置系列配置项
    line.set_series_opts(
        label_opts=opts.LabelOpts(is_show=False))
    # 渲染到notebook、
    line.render('flask_test/templates/line.html')


# 柱状图
def get_bar():
    df_bar = pd.read_excel('flask_test/xlsx_data/first_list_type_data.xlsx')
    df_bar = df_bar.sort_values('播放量', ascending=False).reset_index()
    df = df_bar[['标签', '播放量', '评论', '点赞', '投币', '收藏', '转发']]
    x_data = list(df['标签'])
    y_data = list(df['播放量'])
    y_data1 = list(df['评论'])
    y_data2 = list(df['点赞'])
    y_data3 = list(df['投币'])
    y_data4 = list(df['收藏'])
    y_data5 = list(df['转发'])
    bar = Bar(init_opts=opts.InitOpts(width="1400px", height="720px",
                                      theme=ThemeType.CHALK))
    bar.add_xaxis(x_data)
    bar.add_yaxis(series_name='播放量', y_axis=y_data)
    bar.add_yaxis(series_name='评论', y_axis=y_data1)
    bar.add_yaxis(series_name='点赞', y_axis=y_data2)
    bar.add_yaxis(series_name='投币', y_axis=y_data3)
    bar.add_yaxis(series_name='收藏', y_axis=y_data4)
    bar.add_yaxis(series_name='转发', y_axis=y_data5)
    bar.set_global_opts(title_opts=opts.TitleOpts(title='各类标签对比'),
                        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=30)))
    bar.render('flask_test/templates/bar.html')


# 词云图
def get_WordCloud():
    data = pd.read_excel("flask_test/xlsx_data/list_type.xlsx")
    data_radar = []
    for row in range(data.shape[0]):
        for col in range(1, data.shape[1]):
            value = str(data.iloc[row, col])
        data_radar.append((data["类型"][row], value))

    wordCloud = WordCloud(init_opts=opts.InitOpts(width="900px", height="500px"))

    wordCloud.add(series_name="热点分析", data_pair=data_radar, word_size_range=[6, 66])
    wordCloud.set_global_opts(
        title_opts=opts.TitleOpts(
            title="热点分析", title_textstyle_opts=opts.TextStyleOpts(font_size=23)
        ),
        tooltip_opts=opts.TooltipOpts(is_show=True),
    )
    wordCloud.render("flask_test/templates/basic_wordcloud.html")


# 雷达图
def get_radar():
    data = pd.read_excel("flask_test/xlsx_data/first_list_type_data.xlsx")
    data_name = []
    data_radar = []
    data_color = ['#CD0000', '#00BFFF', '#7B68EE', '#F4A460', '#00FFFF', '#00FA9A',
                  '#ADFF2F', '#FFC0CB', '#FF0000', '#FFF0F5', '#00FF00', '#FFFF00',
                  '#20B2AA', '#00FFFF', '#7FFFD4', '#B0C4DE', '#1E90FF', '#FFF8DC',
                  '#FFE4E1', '#E0FFFF']
    for row in range(data.shape[0]):
        value = []
        for col in range(1, data.shape[1]):
            value.append(int(data.iloc[row, col]))
        data_radar.append(value)
        data_name.append(data["标签"][row])

    scope = []
    for col in range(1, data.shape[1]):
        scope.append(max(data.iloc[:, col]))

    radar = Radar(init_opts=opts.InitOpts(width="1400px", height="720px", theme=ThemeType.CHALK))
    radar.add_schema(
        schema=[
            opts.RadarIndicatorItem(name="播放量（Play volume）", max_=scope[0]),
            opts.RadarIndicatorItem(name="评论数（Number of comments）", max_=scope[1]),
            opts.RadarIndicatorItem(name="点赞数（Give the thumbs-up）", max_=scope[2]),
            opts.RadarIndicatorItem(name="投币（Coin-operated）", max_=scope[3]),
            opts.RadarIndicatorItem(name="收藏（Collection）", max_=scope[4]),
            opts.RadarIndicatorItem(name="转发（Forward）", max_=scope[5]),
        ],
        splitarea_opt=opts.SplitAreaOpts(
            is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
        ),
        textstyle_opts=opts.TextStyleOpts(color="#fff"),
    )

    for i, v2 in enumerate(data_radar, 0):
        radar.add(
            series_name=data_name[i],
            data=[v2],
            linestyle_opts=opts.LineStyleOpts(color=data_color[i]),
        )
    radar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    radar.set_global_opts(
        title_opts=opts.TitleOpts(title="对比标签数据"), legend_opts=opts.LegendOpts()
    )
    radar.render("flask_test/templates/basic_radar_chart.html")


def all_page():
    page = Page(
        page_title="基于python的热门数据分析大屏",
        layout=Page.DraggablePageLayout,  # 拖拽方法
    )
    for i in range(10):
        page.add(
            # tab0("OFFICETOUCH", "#2CB34A"),
            get_radar(),
            # tab1("数据可视化大屏", "#2CB34A"),
            get_WordCloud(),
            get_bar(),
            get_line(),
            get_pie2(i),
            get_pie(),
        )
        page.render("临时大屏.html")
        Page.save_resize_html(
            source="临时大屏.html",
            cfg_file="chart_config.json",
            dest="大屏_最终_0426.html"
        )
        print("生成成功")
        sleep(10)


if __name__ == '__main__':
    # get_radar()
    # get_WordCloud()
    # get_bar()
    # get_line()
    # get_pie2()
    # get_pie()
    all_page()
